package cn.tedu.lonnghospital.appointment.ex.handle;


import cn.tedu.lonnghospital.appointment.ex.ServiceException;
import cn.tedu.lonnghospital.appointment.web.JsonResult;
import cn.tedu.lonnghospital.appointment.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {
    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e) {
        log.warn("程序运行过程中出现了ServiceException，将统一处理！");
        log.warn("异常信息：{}", e.getMessage());
        return JsonResult.fail(e.getServiceCode(),e.getMessage());
    }

    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e) {
        log.warn("程序运行过程中出现了ConstraintViolationException，将统一处理！");
        log.warn("异常信息：{}", e.getMessage());
        String message = null;
        Set<ConstraintViolation<?>> set = e.getConstraintViolations();
        for (ConstraintViolation c : set) {
            message = c.getMessage();
        }
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException e) {
        log.warn("程序运行过程中出现了BindException，将统一处理！");
        log.warn("异常信息：", e);
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,e.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e) {
        log.warn("异常：", e);
        return JsonResult.fail(ServiceCode.ERROR_UNKNOWN,"服务器忙，请稍后再试！【开发中如果看到此提示，应该检查服务器端的控制台，分析异常，并在全局异常处理器中补充对应的方法处理此异常】");
    }
}
